(function(){
  const wv = window.chrome?.webview;
  const $ = s => document.querySelector(s);
  const $$ = s => document.querySelectorAll(s);

  let currentSessionId = newId();

  function newId(){ return Array.from(crypto.getRandomValues(new Uint8Array(8))).map(x=>x.toString(16).padStart(2,'0')).join(''); }
  function send(msg){ wv?.postMessage(JSON.stringify(msg)); }

  function renderSessions(items){
    const box = $('#sessions'); box.innerHTML = '';
    items.forEach(it=>{
      const div = document.createElement('div');
      div.className = 'session-item' + (it.id===currentSessionId?' active':'');
      div.textContent = it.title || ('会话 '+it.id.slice(0,6));
      div.onclick = ()=>{
        currentSessionId = it.id;
        send({type:'openSession', sessionId: currentSessionId});
        $$('.session-item').forEach(el=>el.classList.remove('active'));
        div.classList.add('active');
      };
      box.appendChild(div);
    });
  }

  function addMessage(role, text, streaming=false){
    const m = document.createElement('div');
    m.className = 'msg ' + role + (streaming?' streaming':'');
    m.textContent = text || '';
    $('#messages').appendChild(m);
    $('#messages').scrollTop = $('#messages').scrollHeight;
    return m;
  }

  // UI events
  $('#newChat').onclick = ()=>{
    currentSessionId = newId();
    $('#sessionTitle').textContent = '会话 ' + currentSessionId.slice(0,6);
    $('#messages').innerHTML = '';
    renderSessions([{id: currentSessionId, title: '会话 '+currentSessionId.slice(0,6)}]);
  };

  function doSend(){
    const t = $('#prompt').value.trim();
    if(!t) return;
    $('#prompt').value='';
    send({type:'ask', text: t, sessionId: currentSessionId});
  }
  $('#send').onclick = doSend;
  $('#prompt').addEventListener('keydown', (e)=>{
    if(e.key==='Enter' && !e.shiftKey){
      e.preventDefault();
      doSend();
    }
  });

  // Bridge
  wv?.addEventListener('message', ev=>{
    const data = JSON.parse(ev.data || '{}');
    if(data.type==='sessions'){
      renderSessions(data.items || []);
    }else if(data.type==='loadSession'){
      currentSessionId = data.sessionId;
      $('#sessionTitle').textContent = '会话 ' + currentSessionId.slice(0,6);
      $('#messages').innerHTML='';
      (data.messages||[]).forEach(m=> addMessage(m.role, m.content));
    }else if(data.type==='addUserMessage'){
      addMessage('user', data.content);
    }else if(data.type==='startAssistantMessage'){
      window._streamEl = addMessage('assistant','', true);
    }else if(data.type==='appendAssistantChunk'){
      if(window._streamEl){
        window._streamEl.textContent += data.content || '';
        $('#messages').scrollTop = $('#messages').scrollHeight;
      }
    }else if(data.type==='finishAssistantMessage'){
      if(window._streamEl){ window._streamEl.classList.remove('streaming'); window._streamEl = null; }
    }else if(data.type==='addAssistantMessage'){
      addMessage('assistant', data.content);
    }
  });

  // init
  send({type:'loadSessions'});
  $('#sessionTitle').textContent = '会话 ' + currentSessionId.slice(0,6);
})();